﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Data;

namespace MvvmTreeView.Converters
{
    public class ByteArrayToBitMapConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var binaryData = (byte[])value;

            if (binaryData == null)
            {
                return null;
            }

            BitmapImage bitmap = null;

            if (IsJpegOrPngImage(binaryData))
            {
                Stream stream = null;

                try
                {
                    stream = new MemoryStream(binaryData);
                    bitmap = new BitmapImage();
                    bitmap.SetSource(stream);
                }
                catch (Exception e)
                {
                    bitmap = null;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }

            return bitmap;
        }

        private static bool IsJpegOrPngImage(byte[] binaryData)
        {
            if (binaryData.Length > 2)
            {
                if (binaryData[0].Equals(0XFF) && binaryData[1].Equals(0XD8))
                {
                    return true;
                }

                if (binaryData[0].Equals(0X89) && binaryData[1].Equals(0X50))
                {
                    return true;
                }
            }

            return false;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
